/*
 * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "WorldSession.h"
#include "BattlePetMgr.h"
#include "Common.h"
#include "Creature.h"
#include "DatabaseEnv.h"
#include "DB2Stores.h"
#include "GossipDef.h"
#include "Item.h"
#include "ItemPackets.h"
#include "Log.h"
#include "NPCPackets.h"
#include "ObjectMgr.h"
#include "Player.h"
#include "World.h"

void WorldSession::HandleSplitItemOpcode(WorldPackets::Item::SplitItem& splitItem)
{
    if (!splitItem.Inv.Items.empty())
    {
        TC_LOG_ERROR("network", "HandleSplitItemOpcode - Invalid ItemCount ({})", splitItem.Inv.Items.size());
        return;
    }

    TC_LOG_DEBUG("network", "HandleSplitItemOpcode: receive FromPackSlot: {}, FromSlot: {}, ToPackSlot: {}, ToSlot: {}, Quantity: {}",
        splitItem.FromPackSlot, splitItem.FromSlot, splitItem.ToPackSlot, splitItem.ToSlot, splitItem.Quantity);

    uint16 src = ((splitItem.FromPackSlot << 8) | splitItem.FromSlot);
    uint16 dst = ((splitItem.ToPackSlot << 8) | splitItem.ToSlot);

    if (src == dst)
        return;

    // check count - if zero it's fake packet
    if (!splitItem.Quantity)
        return;

    if (!_player->IsValidPos(splitItem.FromPackSlot, splitItem.FromSlot, true))
    {
        _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND);
        return;
    }

    if (!_player->IsValidPos(splitItem.ToPackSlot, splitItem.ToSlot, false)) // can be autostore pos
    {
        _player->SendEquipError(EQUIP_ERR_WRONG_SLOT);
        return;
    }

    _player->SplitItem(src, dst, splitItem.Quantity);
}

void WorldSession::HandleSwapInvItemOpcode(WorldPackets::Item::SwapInvItem& swapInvItem)
{
    if (swapInvItem.Inv.Items.size() != 2)
    {
        TC_LOG_ERROR("network", "HandleSwapInvItemOpcode - Invalid itemCount ({})", swapInvItem.Inv.Items.size());
        return;
    }

    TC_LOG_DEBUG("network", "HandleSwapInvItemOpcode: receive Slot1: {}, Slot2: {}",
        swapInvItem.Slot1, swapInvItem.Slot2);

    // prevent attempt swap same item to current position generated by client at special checting sequence
    if (swapInvItem.Slot1 == swapInvItem.Slot2)
        return;

    if (!_player->IsValidPos(INVENTORY_SLOT_BAG_0, swapInvItem.Slot1, true))
    {
        _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND);
        return;
    }

    if (!_player->IsValidPos(INVENTORY_SLOT_BAG_0, swapInvItem.Slot2, true))
    {
        _player->SendEquipError(EQUIP_ERR_WRONG_SLOT);
        return;
    }

    if (_player->IsBankPos(INVENTORY_SLOT_BAG_0, swapInvItem.Slot1) && !CanUseBank())
    {
        TC_LOG_DEBUG("network", "HandleSwapInvItemOpcode - Unit ({}) not found or you can't interact with him.", _player->PlayerTalkClass->GetInteractionData().SourceGuid.ToString());
        return;
    }

    if (_player->IsBankPos(INVENTORY_SLOT_BAG_0, swapInvItem.Slot2) && !CanUseBank())
    {
        TC_LOG_DEBUG("network", "HandleSwapInvItemOpcode - Unit ({}) not found or you can't interact with him.", _player->PlayerTalkClass->GetInteractionData().SourceGuid.ToString());
        return;
    }

    uint16 src = ((INVENTORY_SLOT_BAG_0 << 8) | swapInvItem.Slot1);
    uint16 dst = ((INVENTORY_SLOT_BAG_0 << 8) | swapInvItem.Slot2);

    _player->SwapItem(src, dst);
}

void WorldSession::HandleAutoEquipItemSlotOpcode(WorldPackets::Item::AutoEquipItemSlot& autoEquipItemSlot)
{
    // cheating attempt, client should never send opcode in that case
    if (autoEquipItemSlot.Inv.Items.size() != 1 || !Player::IsEquipmentPos(INVENTORY_SLOT_BAG_0, autoEquipItemSlot.ItemDstSlot))
        return;

    Item* item = _player->GetItemByGuid(autoEquipItemSlot.Item);
    uint16 dstPos = autoEquipItemSlot.ItemDstSlot | (INVENTORY_SLOT_BAG_0 << 8);
    uint16 srcPos = autoEquipItemSlot.Inv.Items[0].Slot | (uint32(autoEquipItemSlot.Inv.Items[0].ContainerSlot) << 8);

    if (!item || item->GetPos() != srcPos || srcPos == dstPos)
        return;

    _player->SwapItem(srcPos, dstPos);
}

void WorldSession::HandleSwapItem(WorldPackets::Item::SwapItem& swapItem)
{
    if (swapItem.Inv.Items.size() != 2)
    {
        TC_LOG_ERROR("network", "HandleSwapItem - Invalid itemCount ({})", swapItem.Inv.Items.size());
        return;
    }

    TC_LOG_DEBUG("network", "HandleSwapItem: receive ContainerSlotA: {}, SlotA: {}, ContainerSlotB: {}, SlotB: {}",
        swapItem.ContainerSlotA, swapItem.SlotA, swapItem.ContainerSlotB, swapItem.SlotB);

    uint16 src = ((swapItem.ContainerSlotA << 8) | swapItem.SlotA);
    uint16 dst = ((swapItem.ContainerSlotB << 8) | swapItem.SlotB);

    // prevent attempt swap same item to current position generated by client at special checting sequence
    if (src == dst)
        return;

    if (!_player->IsValidPos(swapItem.ContainerSlotA, swapItem.SlotA, true))
    {
        _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND);
        return;
    }

    if (!_player->IsValidPos(swapItem.ContainerSlotB, swapItem.SlotB, true))
    {
        _player->SendEquipError(EQUIP_ERR_WRONG_SLOT);
        return;
    }

    if (_player->IsBankPos(swapItem.ContainerSlotA, swapItem.SlotA) && !CanUseBank())
    {
        TC_LOG_DEBUG("network", "HandleSwapItem - Unit ({}) not found or you can't interact with him.", _player->PlayerTalkClass->GetInteractionData().SourceGuid.ToString());
        return;
    }

    if (_player->IsBankPos(swapItem.ContainerSlotB, swapItem.SlotB) && !CanUseBank())
    {
        TC_LOG_DEBUG("network", "HandleSwapItem - Unit ({}) not found or you can't interact with him.", _player->PlayerTalkClass->GetInteractionData().SourceGuid.ToString());
        return;
    }

    _player->SwapItem(src, dst);
}

void WorldSession::HandleAutoEquipItemOpcode(WorldPackets::Item::AutoEquipItem& autoEquipItem)
{
    if (autoEquipItem.Inv.Items.size() != 1)
    {
        TC_LOG_ERROR("network", "HandleAutoEquipItemOpcode - Invalid itemCount ({})", autoEquipItem.Inv.Items.size());
        return;
    }

    TC_LOG_DEBUG("network", "HandleAutoEquipItemOpcode: receive PackSlot: {}, Slot: {}",
        autoEquipItem.PackSlot, autoEquipItem.Slot);

    Item* srcItem  = _player->GetItemByPos(autoEquipItem.PackSlot, autoEquipItem.Slot);
    if (!srcItem)
        return;                                         // only at cheat

    uint16 dest;
    InventoryResult msg = _player->CanEquipItem(NULL_SLOT, dest, srcItem, !srcItem->IsBag());
    if (msg != EQUIP_ERR_OK)
    {
        _player->SendEquipError(msg, srcItem);
        return;
    }

    uint16 src = srcItem->GetPos();
    if (dest == src)                                    // prevent equip in same slot, only at cheat
        return;

    Item* dstItem = _player->GetItemByPos(dest);
    if (!dstItem)                                      // empty slot, simple case
    {
        if (!srcItem->GetChildItem().IsEmpty())
        {
            InventoryResult childEquipResult = _player->CanEquipChildItem(srcItem);
            if (childEquipResult != EQUIP_ERR_OK)
            {
                _player->SendEquipError(msg, srcItem);
                return;
            }
        }

        _player->RemoveItem(autoEquipItem.PackSlot, autoEquipItem.Slot, true);
        _player->EquipItem(dest, srcItem, true);
        if (!srcItem->GetChildItem().IsEmpty())
            _player->EquipChildItem(autoEquipItem.PackSlot, autoEquipItem.Slot, srcItem);

        _player->AutoUnequipOffhandIfNeed();
    }
    else                                                    // have currently equipped item, not simple case
    {
        uint8 dstbag = dstItem->GetBagSlot();
        uint8 dstslot = dstItem->GetSlot();

        msg = _player->CanUnequipItem(dest, !srcItem->IsBag());
        if (msg != EQUIP_ERR_OK)
        {
            _player->SendEquipError(msg, dstItem);
            return;
        }

        if (!dstItem->HasItemFlag(ITEM_FIELD_FLAG_CHILD))
        {
            // check dest->src move possibility
            ItemPosCountVec sSrc;
            uint16 eSrc = 0;
            if (_player->IsInventoryPos(src))
            {
                msg = _player->CanStoreItem(autoEquipItem.PackSlot, autoEquipItem.Slot, sSrc, dstItem, true);
                if (msg != EQUIP_ERR_OK)
                    msg = _player->CanStoreItem(autoEquipItem.PackSlot, NULL_SLOT, sSrc, dstItem, true);
                if (msg != EQUIP_ERR_OK)
                    msg = _player->CanStoreItem(NULL_BAG, NULL_SLOT, sSrc, dstItem, true);
            }
            else if (_player->IsBankPos(src))
            {
                msg = _player->CanBankItem(autoEquipItem.PackSlot, autoEquipItem.Slot, sSrc, dstItem, true);
                if (msg != EQUIP_ERR_OK)
                    msg = _player->CanBankItem(autoEquipItem.PackSlot, NULL_SLOT, sSrc, dstItem, true);
                if (msg != EQUIP_ERR_OK)
                    msg = _player->CanBankItem(NULL_BAG, NULL_SLOT, sSrc, dstItem, true);
            }
            else if (_player->IsEquipmentPos(src))
            {
                msg = _player->CanEquipItem(autoEquipItem.Slot, eSrc, dstItem, true);
                if (msg == EQUIP_ERR_OK)
                    msg = _player->CanUnequipItem(eSrc, true);
            }

            if (msg == EQUIP_ERR_OK && Player::IsEquipmentPos(dest) && !srcItem->GetChildItem().IsEmpty())
                msg = _player->CanEquipChildItem(srcItem);

            if (msg != EQUIP_ERR_OK)
            {
                _player->SendEquipError(msg, dstItem, srcItem);
                return;
            }

            // now do moves, remove...
            _player->RemoveItem(dstbag, dstslot, false);
            _player->RemoveItem(autoEquipItem.PackSlot, autoEquipItem.Slot, false);

            // add to dest
            _player->EquipItem(dest, srcItem, true);

            // add to src
            if (_player->IsInventoryPos(src))
                _player->StoreItem(sSrc, dstItem, true);
            else if (_player->IsBankPos(src))
                _player->BankItem(sSrc, dstItem, true);
            else if (_player->IsEquipmentPos(src))
                _player->EquipItem(eSrc, dstItem, true);

            if (Player::IsEquipmentPos(dest) && !srcItem->GetChildItem().IsEmpty())
                _player->EquipChildItem(autoEquipItem.PackSlot, autoEquipItem.Slot, srcItem);
        }
        else
        {
            if (Item* parentItem = _player->GetItemByGuid(dstItem->GetCreator()))
            {
                if (Player::IsEquipmentPos(dest))
                {
                    _player->AutoUnequipChildItem(parentItem);
                    // dest is now empty
                    _player->SwapItem(src, dest);
                    // src is now empty
                    _player->SwapItem(parentItem->GetPos(), src);
                }
            }
        }

        _player->AutoUnequipOffhandIfNeed();

        // if inventory item was moved, check if we can remove dependent auras, because they were not removed in Player::RemoveItem (update was set to false)
        // do this after swaps are done, we pass nullptr because both weapons could be swapped and none of them should be ignored
        if ((autoEquipItem.PackSlot == INVENTORY_SLOT_BAG_0 && autoEquipItem.Slot < INVENTORY_SLOT_BAG_END) || (dstbag == INVENTORY_SLOT_BAG_0 && dstslot < INVENTORY_SLOT_BAG_END))
            _player->ApplyItemDependentAuras((Item*)nullptr, false);
    }
}

void WorldSession::HandleDestroyItemOpcode(WorldPackets::Item::DestroyItem& destroyItem)
{
    TC_LOG_DEBUG("network", "HandleDestroyItemOpcode: receive ContainerId: {}, SlotNum: {}, Count: {}",
        destroyItem.ContainerId, destroyItem.SlotNum, destroyItem.Count);

    uint16 pos = (destroyItem.ContainerId << 8) | destroyItem.SlotNum;

    // prevent drop unequipable items (in combat, for example) and non-empty bags
    if (_player->IsEquipmentPos(pos) || _player->IsBagPos(pos))
    {
        InventoryResult msg = _player->CanUnequipItem(pos, false);
        if (msg != EQUIP_ERR_OK)
        {
            _player->SendEquipError(msg, _player->GetItemByPos(pos));
            return;
        }
    }

    Item* item  = _player->GetItemByPos(destroyItem.ContainerId, destroyItem.SlotNum);
    if (!item)
    {
        _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND);
        return;
    }

    if (item->GetTemplate()->HasFlag(ITEM_FLAG_NO_USER_DESTROY))
    {
        _player->SendEquipError(EQUIP_ERR_DROP_BOUND_ITEM, nullptr, nullptr);
        return;
    }

    if (destroyItem.Count)
    {
        uint32 i_count = destroyItem.Count;
        _player->DestroyItemCount(item, i_count, true);
    }
    else
        _player->DestroyItem(destroyItem.ContainerId, destroyItem.SlotNum, true);
}

void WorldSession::HandleReadItem(WorldPackets::Item::ReadItem& readItem)
{
    Item* item = _player->GetItemByPos(readItem.PackSlot, readItem.Slot);
    if (item && item->GetTemplate()->GetPageText())
    {
        InventoryResult msg = _player->CanUseItem(item);
        if (msg == EQUIP_ERR_OK)
        {
            WorldPackets::Item::ReadItemResultOK packet;
            packet.Item = item->GetGUID();
            SendPacket(packet.Write());

            TC_LOG_INFO("network", "STORAGE: Item page sent");
        }
        else
        {
            /// @todo: 6.x research new values
            /*WorldPackets::Item::ReadItemResultFailed packet;
            packet.Item = item->GetGUID();
            packet.Subcode = ??;
            packet.Delay = ??;
            SendPacket(packet.Write());*/

            TC_LOG_INFO("network", "STORAGE: Unable to read item");
            _player->SendEquipError(msg, item, nullptr);
        }
    }
    else
        _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr);
}

void WorldSession::HandleSellItemOpcode(WorldPackets::Item::SellItem& packet)
{
    TC_LOG_DEBUG("network", "WORLD: Received CMSG_SELL_ITEM: Vendor {}, Item {}, Amount: {}",
        packet.VendorGUID.ToString(), packet.ItemGUID.ToString(), packet.Amount);

    if (packet.ItemGUID.IsEmpty())
        return;

    Creature* creature = GetPlayer()->GetNPCIfCanInteractWith(packet.VendorGUID, UNIT_NPC_FLAG_VENDOR, UNIT_NPC_FLAG_2_NONE);
    if (!creature)
    {
        TC_LOG_DEBUG("network", "WORLD: HandleSellItemOpcode - {} not found or you can not interact with him.", packet.VendorGUID.ToString());
        _player->SendSellError(SELL_ERR_CANT_FIND_VENDOR, nullptr, packet.ItemGUID);
        return;
    }

    if ((creature->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_NO_SELL_VENDOR) != 0)
    {
        _player->SendSellError(SELL_ERR_CANT_SELL_TO_THIS_MERCHANT, creature, packet.ItemGUID);
        return;
    }

    // remove fake death
    if (GetPlayer()->HasUnitState(UNIT_STATE_DIED))
        GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH);

    Item* pItem = _player->GetItemByGuid(packet.ItemGUID);
    if (pItem)
    {
        // prevent sell not owner item
        if (_player->GetGUID() != pItem->GetOwnerGUID())
        {
            _player->SendSellError(SELL_ERR_CANT_SELL_ITEM, creature, packet.ItemGUID);
            return;
        }

        // prevent sell non empty bag by drag-and-drop at vendor's item list
        if (pItem->IsNotEmptyBag())
        {
            _player->SendSellError(SELL_ERR_CANT_SELL_ITEM, creature, packet.ItemGUID);
            return;
        }

        // prevent sell currently looted item
        if (_player->GetLootGUID() == pItem->GetGUID())
        {
            _player->SendSellError(SELL_ERR_CANT_SELL_ITEM, creature, packet.ItemGUID);
            return;
        }

        // prevent selling item for sellprice when the item is still refundable
        // this probably happens when right clicking a refundable item, the client sends both
        // CMSG_SELL_ITEM and CMSG_REFUND_ITEM (unverified)
        if (pItem->IsRefundable())
            return; // Therefore, no feedback to client

        // special case at auto sell (sell all)
        if (packet.Amount == 0)
            packet.Amount = pItem->GetCount();
        else
        {
            // prevent sell more items that exist in stack (possible only not from client)
            if (packet.Amount > pItem->GetCount())
            {
                _player->SendSellError(SELL_ERR_CANT_SELL_ITEM, creature, packet.ItemGUID);
                return;
            }
        }

        if (uint32 sellPrice = pItem->GetSellPrice(_player); sellPrice > 0)
        {
            uint64 money = uint64(sellPrice) * packet.Amount;

            using BuybackStorageType = std::remove_cvref_t<decltype(_player->m_activePlayerData->BuybackPrice[0])>;
            if (money > std::numeric_limits<BuybackStorageType>::max()) // ensure sell price * amount doesn't overflow buyback price
            {
                _player->SendSellError(SELL_ERR_CANT_SELL_ITEM, creature, packet.ItemGUID);
                return;
            }

            if (!_player->ModifyMoney(money)) // ensure player doesn't exceed gold limit
            {
                _player->SendSellError(SELL_ERR_CANT_SELL_ITEM, creature, packet.ItemGUID);
                return;
            }

            _player->UpdateCriteria(CriteriaType::MoneyEarnedFromSales, money);
            _player->UpdateCriteria(CriteriaType::SellItemsToVendors, 1);

            if (packet.Amount < pItem->GetCount())               // need split items
            {
                Item* pNewItem = pItem->CloneItem(packet.Amount, _player);
                if (!pNewItem)
                {
                    TC_LOG_ERROR("network", "WORLD: HandleSellItemOpcode - could not create clone of item {}; count = {}", pItem->GetEntry(), packet.Amount);
                    _player->SendSellError(SELL_ERR_CANT_SELL_ITEM, creature, packet.ItemGUID);
                    return;
                }

                pItem->SetCount(pItem->GetCount() - packet.Amount);
                _player->ItemRemovedQuestCheck(pItem->GetEntry(), packet.Amount);
                if (_player->IsInWorld())
                    pItem->SendUpdateToPlayer(_player);
                pItem->SetState(ITEM_CHANGED, _player);

                _player->AddItemToBuyBackSlot(pNewItem);
                if (_player->IsInWorld())
                    pNewItem->SendUpdateToPlayer(_player);
            }
            else
            {
                _player->RemoveItem(pItem->GetBagSlot(), pItem->GetSlot(), true);
                _player->ItemRemovedQuestCheck(pItem->GetEntry(), pItem->GetCount());
                RemoveItemFromUpdateQueueOf(pItem, _player);
                _player->AddItemToBuyBackSlot(pItem);
            }
        }
        else
            _player->SendSellError(SELL_ERR_CANT_SELL_ITEM, creature, packet.ItemGUID);
        return;
    }
    _player->SendSellError(SELL_ERR_CANT_FIND_ITEM, creature, packet.ItemGUID);
    return;
}

void WorldSession::HandleBuybackItem(WorldPackets::Item::BuyBackItem& packet)
{
    TC_LOG_DEBUG("network", "WORLD: Received CMSG_BUYBACK_ITEM: Vendor {}, Slot: {}", packet.VendorGUID.ToString(), packet.Slot);

    Creature* creature = GetPlayer()->GetNPCIfCanInteractWith(packet.VendorGUID, UNIT_NPC_FLAG_VENDOR, UNIT_NPC_FLAG_2_NONE);
    if (!creature)
    {
        TC_LOG_DEBUG("network", "WORLD: HandleBuybackItem - Unit ({}) not found or you can not interact with him.", packet.VendorGUID.ToString());
        _player->SendSellError(SELL_ERR_CANT_FIND_VENDOR, nullptr, ObjectGuid::Empty);
        return;
    }

    // remove fake death
    if (GetPlayer()->HasUnitState(UNIT_STATE_DIED))
        GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH);

    Item* pItem = _player->GetItemFromBuyBackSlot(packet.Slot);
    if (pItem)
    {
        uint32 price = _player->m_activePlayerData->BuybackPrice[packet.Slot - BUYBACK_SLOT_START];
        if (!_player->HasEnoughMoney(uint64(price)))
        {
            _player->SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, creature, pItem->GetEntry(), 0);
            return;
        }

        ItemPosCountVec dest;
        InventoryResult msg = _player->CanStoreItem(NULL_BAG, NULL_SLOT, dest, pItem, false);
        if (msg == EQUIP_ERR_OK)
        {
            _player->ModifyMoney(-(int32)price);
            _player->RemoveItemFromBuyBackSlot(packet.Slot, false);
            _player->ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
            _player->StoreItem(dest, pItem, true);
        }
        else
            _player->SendEquipError(msg, pItem, nullptr);
        return;
    }
    else
        _player->SendBuyError(BUY_ERR_CANT_FIND_ITEM, creature, 0, 0);
}

void WorldSession::HandleBuyItemOpcode(WorldPackets::Item::BuyItem& packet)
{
    // client expects count starting at 1, and we send vendorslot+1 to client already
    if (packet.Muid > 0)
        --packet.Muid;
    else
        return; // cheating

    switch (packet.ItemType)
    {
        case ITEM_VENDOR_TYPE_ITEM:
        {
            Item* bagItem = _player->GetItemByGuid(packet.ContainerGUID);

            uint8 bag = NULL_BAG;
            if (bagItem && bagItem->IsBag())
                bag = bagItem->GetSlot();
            else if (packet.ContainerGUID == GetPlayer()->GetGUID()) // The client sends the player guid when trying to store an item in the default backpack
                bag = INVENTORY_SLOT_BAG_0;

            GetPlayer()->BuyItemFromVendorSlot(packet.VendorGUID, packet.Muid, packet.Item.ItemID,
                packet.Quantity, bag, packet.Slot);
            break;
        }
        case ITEM_VENDOR_TYPE_CURRENCY:
        {
            GetPlayer()->BuyCurrencyFromVendorSlot(packet.VendorGUID, packet.Muid, packet.Item.ItemID, packet.Quantity);
            break;
        }
        default:
        {
            TC_LOG_DEBUG("network", "WORLD: received wrong itemType ({}) in HandleBuyItemOpcode", packet.ItemType);
            break;
        }
    }
}

void WorldSession::HandleListInventoryOpcode(WorldPackets::NPC::Hello& packet)
{
    if (!GetPlayer()->IsAlive())
        return;

    SendListInventory(packet.Unit);
}

void WorldSession::SendListInventory(ObjectGuid vendorGuid)
{
    Creature* vendor = GetPlayer()->GetNPCIfCanInteractWith(vendorGuid, UNIT_NPC_FLAG_VENDOR, UNIT_NPC_FLAG_2_NONE);
    if (!vendor)
    {
        TC_LOG_DEBUG("network", "WORLD: SendListInventory - {} not found or you can not interact with him.", vendorGuid.ToString());
        _player->SendSellError(SELL_ERR_CANT_FIND_VENDOR, nullptr, ObjectGuid::Empty);
        return;
    }

    // remove fake death
    if (GetPlayer()->HasUnitState(UNIT_STATE_DIED))
        GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH);

    // Stop the npc if moving
    if (uint32 pause = vendor->GetMovementTemplate().GetInteractionPauseTimer())
        vendor->PauseMovement(pause);
    vendor->SetHomePosition(vendor->GetPosition());

    VendorItemData const* vendorItems = vendor->GetVendorItems();
    uint32 rawItemCount = vendorItems ? vendorItems->GetItemCount() : 0;

    WorldPackets::NPC::VendorInventory packet;
    packet.Vendor = vendor->GetGUID();

    packet.Items.resize(rawItemCount);

    const float discountMod = _player->GetReputationPriceDiscount(vendor);
    uint8 count = 0;
    for (uint32 slot = 0; slot < rawItemCount; ++slot)
    {
        VendorItem const* vendorItem = vendorItems->GetItem(slot);
        if (!vendorItem)
            continue;

        WorldPackets::NPC::VendorItem& item = packet.Items[count];

        if (!ConditionMgr::IsPlayerMeetingCondition(_player, vendorItem->PlayerConditionId))
            item.PlayerConditionFailed = vendorItem->PlayerConditionId;

        if (vendorItem->Type == ITEM_VENDOR_TYPE_ITEM)
        {
            ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(vendorItem->item);
            if (!itemTemplate)
                continue;

            int32 leftInStock = !vendorItem->maxcount ? -1 : vendor->GetVendorItemCurrentCount(vendorItem);
            if (!_player->IsGameMaster()) // ignore conditions if GM on
            {
                // Respect allowed class
                if (!(itemTemplate->GetAllowableClass() & _player->GetClassMask()) && itemTemplate->GetBonding() == BIND_ON_ACQUIRE)
                    continue;

                // Only display items in vendor lists for the team the player is on
                if ((itemTemplate->HasFlag(ITEM_FLAG2_FACTION_HORDE) && _player->GetTeam() == ALLIANCE) ||
                    (itemTemplate->HasFlag(ITEM_FLAG2_FACTION_ALLIANCE) && _player->GetTeam() == HORDE))
                    continue;

                // Items sold out are not displayed in list
                if (leftInStock == 0)
                    continue;
            }

            if (!sConditionMgr->IsObjectMeetingVendorItemConditions(vendor->GetEntry(), vendorItem->item, _player, vendor))
            {
                TC_LOG_DEBUG("condition", "SendListInventory: conditions not met for creature entry {} item {}", vendor->GetEntry(), vendorItem->item);
                continue;
            }

            uint64 price = uint64(floor(itemTemplate->GetBuyPrice() * discountMod));
            price = itemTemplate->GetBuyPrice() > 0 ? std::max(uint64(1), price) : price;

            if (int32 priceMod = _player->GetTotalAuraModifier(SPELL_AURA_MOD_VENDOR_ITEMS_PRICES))
                price -= CalculatePct(price, priceMod);

            item.MuID = slot + 1; // client expects counting to start at 1
            item.Durability = itemTemplate->MaxDurability;
            item.ExtendedCostID = vendorItem->ExtendedCost;
            item.Type = vendorItem->Type;
            item.Quantity = leftInStock;
            item.StackCount = itemTemplate->GetBuyCount();
            item.Price = price;
            item.DoNotFilterOnVendor = vendorItem->IgnoreFiltering;
            item.Refundable = itemTemplate->HasFlag(ITEM_FLAG_ITEM_PURCHASE_RECORD) && vendorItem->ExtendedCost && itemTemplate->GetMaxStackSize() == 1;

            item.Item.ItemID = vendorItem->item;
            if (!vendorItem->BonusListIDs.empty())
            {
                item.Item.ItemBonus.emplace();
                item.Item.ItemBonus->BonusListIDs = vendorItem->BonusListIDs;
            }
        }
        else if (vendorItem->Type == ITEM_VENDOR_TYPE_CURRENCY)
        {
            CurrencyTypesEntry const* currencyTemplate = sCurrencyTypesStore.LookupEntry(vendorItem->item);
            if (!currencyTemplate)
                continue;

            if (!vendorItem->ExtendedCost)
                continue; // there's no price defined for currencies, only extendedcost is used

            item.MuID = slot + 1; // client expects counting to start at 1
            item.ExtendedCostID = vendorItem->ExtendedCost;
            item.Item.ItemID = vendorItem->item;
            item.Type = vendorItem->Type;
            item.StackCount = vendorItem->maxcount;
            item.DoNotFilterOnVendor = vendorItem->IgnoreFiltering;
        }
        else
            continue;

        if (++count >= MAX_VENDOR_ITEMS)
            break;
    }

    // Resize vector to real size (some items can be skipped due to checks)
    packet.Items.resize(count);

    packet.Reason = AsUnderlyingType(count ? VendorInventoryReason::None : VendorInventoryReason::Empty);

    SendPacket(packet.Write());
}

void WorldSession::HandleAutoStoreBagItemOpcode(WorldPackets::Item::AutoStoreBagItem& packet)
{
    if (!packet.Inv.Items.empty())
    {
        TC_LOG_ERROR("network", "HandleAutoStoreBagItemOpcode - Invalid itemCount ({})", packet.Inv.Items.size());
        return;
    }

    TC_LOG_DEBUG("network", "HandleAutoStoreBagItemOpcode: receive ContainerSlotA: {}, SlotA: {}, ContainerSlotB: {}",
        packet.ContainerSlotA, packet.SlotA, packet.ContainerSlotB);

    Item* item = _player->GetItemByPos(packet.ContainerSlotA, packet.SlotA);
    if (!item)
        return;

    if (!_player->IsValidPos(packet.ContainerSlotB, NULL_SLOT, false))      // can be autostore pos
    {
        _player->SendEquipError(EQUIP_ERR_WRONG_SLOT);
        return;
    }

    uint16 src = item->GetPos();

    // check unequip potability for equipped items and bank bags
    if (_player->IsEquipmentPos(src) || _player->IsBagPos(src))
    {
        InventoryResult msg = _player->CanUnequipItem(src, !_player->IsBagPos(src));
        if (msg != EQUIP_ERR_OK)
        {
            _player->SendEquipError(msg, item);
            return;
        }
    }

    ItemPosCountVec dest;
    InventoryResult msg = _player->CanStoreItem(packet.ContainerSlotB, NULL_SLOT, dest, item, false);
    if (msg != EQUIP_ERR_OK)
    {
        _player->SendEquipError(msg, item);
        return;
    }

    // no-op: placed in same slot
    if (dest.size() == 1 && dest[0].pos == src)
    {
        // just remove grey item state
        _player->SendEquipError(EQUIP_ERR_INTERNAL_BAG_ERROR, item);
        return;
    }

    _player->RemoveItem(packet.ContainerSlotA, packet.SlotA, true);
    _player->StoreItem(dest, item, true);
}

void WorldSession::SendEnchantmentLog(ObjectGuid owner, ObjectGuid caster, ObjectGuid itemGuid, uint32 itemId, uint32 enchantId, uint32 enchantSlot)
{
    WorldPackets::Item::EnchantmentLog enchantmentLog;
    enchantmentLog.Owner = owner;
    enchantmentLog.Caster = caster;
    enchantmentLog.ItemGUID = itemGuid;
    enchantmentLog.ItemID = itemId;
    enchantmentLog.Enchantment = enchantId;
    enchantmentLog.EnchantSlot = enchantSlot;
    GetPlayer()->SendMessageToSet(enchantmentLog.Write(), true);
}

void WorldSession::SendItemEnchantTimeUpdate(ObjectGuid Playerguid, ObjectGuid Itemguid, uint32 slot, uint32 Duration)
{
    WorldPackets::Item::ItemEnchantTimeUpdate data;
    data.ItemGuid = Itemguid;
    data.DurationLeft = Duration;
    data.Slot = slot;
    data.OwnerGuid = Playerguid;
    SendPacket(data.Write());
}

void WorldSession::HandleWrapItem(WorldPackets::Item::WrapItem& packet)
{
    if (packet.Inv.Items.size() != 2)
    {
        TC_LOG_ERROR("network", "HandleWrapItem - Invalid itemCount ({})", packet.Inv.Items.size());
        return;
    }

    /// @todo: 6.x find better way for read
    // Gift
    uint8 giftContainerSlot = packet.Inv.Items[0].ContainerSlot;
    uint8 giftSlot          = packet.Inv.Items[0].Slot;
    // Item
    uint8 itemContainerSlot = packet.Inv.Items[1].ContainerSlot;
    uint8 itemSlot          = packet.Inv.Items[1].Slot;

    TC_LOG_DEBUG("network", "HandleWrapItem - Receive giftContainerSlot = {}, giftSlot = {}, itemContainerSlot = {}, itemSlot = {}", giftContainerSlot, giftSlot, itemContainerSlot, itemSlot);

    Item* gift = _player->GetItemByPos(giftContainerSlot, giftSlot);
    if (!gift)
    {
        _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, gift, nullptr);
        return;
    }

    if (!gift->GetTemplate()->HasFlag(ITEM_FLAG_IS_WRAPPER)) // cheating: non-wrapper wrapper
    {
        _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, gift, nullptr);
        return;
    }

    Item* item = _player->GetItemByPos(itemContainerSlot, itemSlot);
    if (!item)
    {
        _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, item, nullptr);
        return;
    }

    if (item == gift) // not possable with pacjket from real client
    {
        _player->SendEquipError(EQUIP_ERR_CANT_WRAP_WRAPPED, item, nullptr);
        return;
    }

    if (item->IsEquipped())
    {
        _player->SendEquipError(EQUIP_ERR_CANT_WRAP_EQUIPPED, item, nullptr);
        return;
    }

    if (!item->GetGiftCreator().IsEmpty()) // HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED);
    {
        _player->SendEquipError(EQUIP_ERR_CANT_WRAP_WRAPPED, item, nullptr);
        return;
    }

    if (item->IsBag())
    {
        _player->SendEquipError(EQUIP_ERR_CANT_WRAP_BAGS, item, nullptr);
        return;
    }

    if (item->IsSoulBound())
    {
        _player->SendEquipError(EQUIP_ERR_CANT_WRAP_BOUND, item, nullptr);
        return;
    }

    if (item->GetMaxStackCount() != 1)
    {
        _player->SendEquipError(EQUIP_ERR_CANT_WRAP_STACKABLE, item, nullptr);
        return;
    }

    // maybe not correct check  (it is better than nothing)
    if (item->GetTemplate()->GetMaxCount() > 0)
    {
        _player->SendEquipError(EQUIP_ERR_CANT_WRAP_UNIQUE, item, nullptr);
        return;
    }

    CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction();

    CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_GIFT);
    stmt->setUInt64(0, item->GetOwnerGUID().GetCounter());
    stmt->setUInt64(1, item->GetGUID().GetCounter());
    stmt->setUInt32(2, item->GetEntry());
    stmt->setUInt32(3, item->m_itemData->DynamicFlags);
    trans->Append(stmt);

    item->SetEntry(gift->GetEntry());

    //Replace 'magic value' by enum value
    switch (item->GetEntry())
    {
         case ITEM_RED_RIBBONED_WRAPPING_PAPER:
            item->SetEntry(ITEM_RED_RIBBONED_GIFT);
            break;
        case ITEM_BLUE_RIBBONED_WRAPPING_PAPER:
            item->SetEntry(ITEM_BLUE_RIBBONED_GIFT);
            break;
        case ITEM_BLUE_RIBBONED_HOLIDAY_WRAPPING_PAPER:
            item->SetEntry(ITEM_BLUE_RIBBONED_HOLIDAY_GIFT);
            break;
        case ITEM_GREEN_RIBBONED_WRAPPING_PAPER:
            item->SetEntry(ITEM_GREEN_RIBBONED_HOLIDAY_GIFT);
            break;
        case ITEM_PURPLE_RIBBONED_WRAPPING_PAPER:
            item->SetEntry(ITEM_PURPLE_RIBBONED_HOLIDAY_GIFT);
            break;
        case ITEM_EMPTY_WRAPPER:
            item->SetEntry(ITEM_WRAPPED_GIFT);
            break;
    }

    item->SetGiftCreator(_player->GetGUID());
    item->ReplaceAllItemFlags(ITEM_FIELD_FLAG_WRAPPED);
    item->SetState(ITEM_CHANGED, _player);

    if (item->GetState() == ITEM_NEW) // save new item, to have alway for `character_gifts` record in `item_instance`
    {
        // after save it will be impossible to remove the item from the queue
        RemoveItemFromUpdateQueueOf(item, _player);
        item->SaveToDB(trans);                                   // item gave inventory record unchanged and can be save standalone
    }
    CharacterDatabase.CommitTransaction(trans);

    uint32 count = 1;
    _player->DestroyItemCount(gift, count, true);
}

void WorldSession::HandleSocketGems(WorldPackets::Item::SocketGems& socketGems)
{
    if (!socketGems.ItemGuid)
        return;

    //cheat -> tried to socket same gem multiple times
    if ((!socketGems.GemItem[0].IsEmpty() && (socketGems.GemItem[0] == socketGems.GemItem[1] || socketGems.GemItem[0] == socketGems.GemItem[2])) ||
        (!socketGems.GemItem[1].IsEmpty() && (socketGems.GemItem[1] == socketGems.GemItem[2])))
        return;

    Item* itemTarget = _player->GetItemByGuid(socketGems.ItemGuid);
    if (!itemTarget)                                         //missing item to socket
        return;

    ItemTemplate const* itemProto = itemTarget->GetTemplate();
    if (!itemProto)
        return;

    //this slot is excepted when applying / removing meta gem bonus
    uint8 slot = itemTarget->IsEquipped() ? itemTarget->GetSlot() : uint8(NULL_SLOT);

    Item* gems[MAX_GEM_SOCKETS];
    memset(gems, 0, sizeof(gems));
    ItemDynamicFieldGems gemData[MAX_GEM_SOCKETS];
    memset(gemData, 0, sizeof(gemData));
    GemPropertiesEntry const* gemProperties[MAX_GEM_SOCKETS];
    memset(gemProperties, 0, sizeof(gemProperties));
    UF::SocketedGem const* oldGemData[MAX_GEM_SOCKETS];
    memset(oldGemData, 0, sizeof(oldGemData));
    for (uint32 i = 0; i < MAX_GEM_SOCKETS; ++i)
    {
        if (Item* gem = _player->GetItemByGuid(socketGems.GemItem[i]))
        {
            gems[i] = gem;
            gemData[i].ItemId = gem->GetEntry();
            gemData[i].Context = gem->m_itemData->Context;
            for (std::size_t b = 0; b < gem->GetBonusListIDs().size() && b < 16; ++b)
                gemData[i].BonusListIDs[b] = gem->GetBonusListIDs()[b];

            gemProperties[i] = sGemPropertiesStore.LookupEntry(gem->GetTemplate()->GetGemProperties());
        }

        oldGemData[i] = itemTarget->GetGem(i);
    }

    // Find first prismatic socket
    uint32 firstPrismatic = 0;
    while (firstPrismatic < MAX_GEM_SOCKETS && itemTarget->GetSocketColor(firstPrismatic))
        ++firstPrismatic;

    for (uint32 i = 0; i < MAX_GEM_SOCKETS; ++i)                //check for hack maybe
    {
        if (!gemProperties[i])
            continue;

        // tried to put gem in socket where no socket exists (take care about prismatic sockets)
        if (!itemTarget->GetSocketColor(i))
        {
            // no prismatic socket
            if (!itemTarget->GetEnchantmentId(PRISMATIC_ENCHANTMENT_SLOT))
                return;

            if (i != firstPrismatic)
                return;
        }

        // Gem must match socket color
        if (SocketColorToGemTypeMask[itemTarget->GetSocketColor(i)] != gemProperties[i]->Type)
        {
            // unless its red, blue, yellow or prismatic
            if (!(SocketColorToGemTypeMask[itemTarget->GetSocketColor(i)] & SOCKET_COLOR_PRISMATIC) || !(gemProperties[i]->Type & SOCKET_COLOR_PRISMATIC))
                return;
        }
    }

    // check unique-equipped conditions
    for (uint32 i = 0; i < MAX_GEM_SOCKETS; ++i)
    {
        if (!gems[i])
            continue;

        // continue check for case when attempt add 2 similar unique equipped gems in one item.
        ItemTemplate const* iGemProto = gems[i]->GetTemplate();

        // unique item (for new and already placed bit removed enchantments
        if (iGemProto->HasFlag(ITEM_FLAG_UNIQUE_EQUIPPABLE))
        {
            for (uint32 j = 0; j < MAX_GEM_SOCKETS; ++j)
            {
                if (i == j)                                    // skip self
                    continue;

                if (gems[j])
                {
                    if (iGemProto->GetId() == gems[j]->GetEntry())
                    {
                        _player->SendEquipError(EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED, itemTarget, nullptr);
                        return;
                    }
                }
                else if (oldGemData[j])
                {
                    if (int32(iGemProto->GetId()) == oldGemData[j]->ItemID)
                    {
                        _player->SendEquipError(EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED, itemTarget, nullptr);
                        return;
                    }
                }
            }
        }

        // unique limit type item
        int32 limit_newcount = 0;
        if (iGemProto->GetItemLimitCategory())
        {
            if (ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(iGemProto->GetItemLimitCategory()))
            {
                // NOTE: limitEntry->Flags is not checked because if item has limit then it is applied in equip case
                for (int j = 0; j < MAX_GEM_SOCKETS; ++j)
                {
                    if (gems[j])
                    {
                        // new gem
                        if (iGemProto->GetItemLimitCategory() == gems[j]->GetTemplate()->GetItemLimitCategory())
                            ++limit_newcount;
                    }
                    else if (oldGemData[j])
                    {
                        // existing gem
                        if (ItemTemplate const* jProto = sObjectMgr->GetItemTemplate(oldGemData[j]->ItemID))
                            if (iGemProto->GetItemLimitCategory() == jProto->GetItemLimitCategory())
                                ++limit_newcount;
                    }
                }

                if (limit_newcount > 0 && uint32(limit_newcount) > _player->GetItemLimitCategoryQuantity(limitEntry))
                {
                    _player->SendEquipError(EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED, itemTarget, nullptr);
                    return;
                }
            }
        }

        // for equipped item check all equipment for duplicate equipped gems
        if (itemTarget->IsEquipped())
        {
            if (InventoryResult res = _player->CanEquipUniqueItem(gems[i], slot, std::max(limit_newcount, 0)))
            {
                _player->SendEquipError(res, itemTarget, nullptr);
                return;
            }
        }
    }

    bool SocketBonusActivated = itemTarget->GemsFitSockets();    //save state of socketbonus
    _player->ToggleMetaGemsActive(slot, false);             //turn off all metagems (except for the target item)

    //if a meta gem is being equipped, all information has to be written to the item before testing if the conditions for the gem are met

    //remove ALL mods - gem can change item level
    if (itemTarget->IsEquipped())
        _player->_ApplyItemMods(itemTarget, itemTarget->GetSlot(), false);

    for (uint16 i = 0; i < MAX_GEM_SOCKETS; ++i)
    {
        if (gems[i])
        {
            uint32 gemScalingLevel = _player->GetLevel();
            if (uint32 fixedLevel = gems[i]->GetModifier(ITEM_MODIFIER_TIMEWALKER_LEVEL))
                gemScalingLevel = fixedLevel;

            itemTarget->SetGem(i, &gemData[i], gemScalingLevel);

            if (gemProperties[i] && gemProperties[i]->EnchantId)
                itemTarget->SetEnchantment(EnchantmentSlot(SOCK_ENCHANTMENT_SLOT + i), gemProperties[i]->EnchantId, 0, 0, _player->GetGUID());

            uint32 gemCount = 1;
            _player->DestroyItemCount(gems[i], gemCount, true);
        }
    }

    if (itemTarget->IsEquipped())
        _player->_ApplyItemMods(itemTarget, itemTarget->GetSlot(), true);

    if (Item* childItem = _player->GetChildItemByGuid(itemTarget->GetChildItem()))
    {
        if (childItem->IsEquipped())
            _player->_ApplyItemMods(childItem, childItem->GetSlot(), false);
        childItem->CopyArtifactDataFromParent(itemTarget);
        if (childItem->IsEquipped())
            _player->_ApplyItemMods(childItem, childItem->GetSlot(), true);
    }

    bool SocketBonusToBeActivated = itemTarget->GemsFitSockets();//current socketbonus state
    if (SocketBonusActivated ^ SocketBonusToBeActivated)     //if there was a change...
    {
        _player->ApplyEnchantment(itemTarget, BONUS_ENCHANTMENT_SLOT, false);
        itemTarget->SetEnchantment(BONUS_ENCHANTMENT_SLOT, (SocketBonusToBeActivated ? itemTarget->GetTemplate()->GetSocketBonus() : 0), 0, 0, _player->GetGUID());
        _player->ApplyEnchantment(itemTarget, BONUS_ENCHANTMENT_SLOT, true);
        //it is not displayed, client has an inbuilt system to determine if the bonus is activated
    }

    _player->ToggleMetaGemsActive(slot, true);              //turn on all metagems (except for target item)

    _player->RemoveTradeableItem(itemTarget);
    itemTarget->ClearSoulboundTradeable(_player);           // clear tradeable flag

    itemTarget->SendUpdateSockets();
}

void WorldSession::HandleCancelTempEnchantmentOpcode(WorldPackets::Item::CancelTempEnchantment& cancelTempEnchantment)
{
    // apply only to equipped item
    if (!Player::IsEquipmentPos(INVENTORY_SLOT_BAG_0, cancelTempEnchantment.Slot))
        return;

    Item* item = GetPlayer()->GetItemByPos(INVENTORY_SLOT_BAG_0, cancelTempEnchantment.Slot);

    if (!item)
        return;

    if (!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
        return;

    GetPlayer()->ApplyEnchantment(item, TEMP_ENCHANTMENT_SLOT, false);
    item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
}

void WorldSession::HandleGetItemPurchaseData(WorldPackets::Item::GetItemPurchaseData& packet)
{
    Item* item = _player->GetItemByGuid(packet.ItemGUID);
    if (!item)
    {
        TC_LOG_DEBUG("network", "HandleGetItemPurchaseData: Item {} not found!", packet.ItemGUID.ToString());
        return;
    }

    TC_LOG_DEBUG("network", "HandleGetItemPurchaseData: Item {}", packet.ItemGUID.ToString());

    GetPlayer()->SendRefundInfo(item);
}

void WorldSession::HandleItemRefund(WorldPackets::Item::ItemPurchaseRefund& packet)
{
    Item* item = _player->GetItemByGuid(packet.ItemGUID);
    if (!item)
    {
        TC_LOG_DEBUG("network", "WorldSession::HandleItemRefund: Item ({}) not found!", packet.ItemGUID.ToString());
        return;
    }

    // Don't try to refund item currently being disenchanted
    if (_player->GetLootGUID() == packet.ItemGUID)
        return;

    GetPlayer()->RefundItem(item);
}

bool WorldSession::CanUseBank(ObjectGuid bankerGUID) const
{
    // bankerGUID parameter is optional, set to 0 by default.
    if (!bankerGUID)
        bankerGUID = _player->PlayerTalkClass->GetInteractionData().SourceGuid;

    bool isUsingBankCommand = (bankerGUID == GetPlayer()->GetGUID() && bankerGUID == _player->PlayerTalkClass->GetInteractionData().SourceGuid);

    if (!isUsingBankCommand)
    {
        Creature* creature = GetPlayer()->GetNPCIfCanInteractWith(bankerGUID, UNIT_NPC_FLAG_BANKER, UNIT_NPC_FLAG_2_NONE);
        if (!creature)
            return false;
    }

    return true;
}

void WorldSession::HandleUseCritterItem(WorldPackets::Item::UseCritterItem& useCritterItem)
{
    Item* item = _player->GetItemByGuid(useCritterItem.ItemGuid);
    if (!item)
        return;

    for (ItemEffectEntry const* itemEffect : item->GetEffects())
   {
        if (itemEffect->TriggerType != ITEM_SPELLTRIGGER_ON_LEARN)
            continue;

        if (BattlePetSpeciesEntry const* speciesEntry = BattlePets::BattlePetMgr::GetBattlePetSpeciesBySpell(uint32(itemEffect->SpellID)))
            GetBattlePetMgr()->AddPet(speciesEntry->ID, BattlePets::BattlePetMgr::SelectPetDisplay(speciesEntry),
                BattlePets::BattlePetMgr::RollPetBreed(speciesEntry->ID), BattlePets::BattlePetMgr::GetDefaultPetQuality(speciesEntry->ID));
    }

    _player->DestroyItem(item->GetBagSlot(), item->GetSlot(), true);
}

void WorldSession::HandleSortBags(WorldPackets::Item::SortBags& /*sortBags*/)
{
        std::multimap<uint64, Item*> items;
    uint32 sortOrderHi;
    uint32 sortOrderLo;
    uint64 sortOrder;
    uint8 endbackpackSlot = INVENTORY_SLOT_ITEM_START + _player->GetInventorySlotCount();
    /*
    * The sorting order is:
    * 1 - the special Items (hearthstones, etc.)
    * 2 - Consumables ordered by subclass then item id
    * 3 - Weapons and Shield
    * 4 - Armor ordered by item level in descending order
    *  4.01 - Head
    *  4.02 - Shoulders
    *  4.03 - Chest and Robe
    *  4.04 - Wrists
    *  4.05 - Hands
    *  4.06 - Waist
    *  4.07 - Legs
    *  4.08 - Feet
    *  4.09 - Cloak
    *  4.10 - Accessory (Neck, finger then trinkets)
    *  4.11 - Shirt and Tabard (order by item id)
    * 5 - All other items order by class (ascending) and subclass (descending) then item id (descending)
    */

    if (!_player->IsBackpackAutoSortDisabled())
        for (uint8 slot = INVENTORY_SLOT_ITEM_START; slot < endbackpackSlot; slot++)
        {
            if (Item* item = _player->GetItemByPos(INVENTORY_SLOT_BAG_0, slot))
            {
                if (item->GetEntry() == ITEM_HEARTHSTONE || item->GetEntry() == ITEM_GARRISON_HEARTHSTONE
                    || item->GetEntry() == ITEM_DALARAN_HEARTHSTONE || item->GetEntry() == ITEM_FLIGHT_MASTER_WHISTLE)
                {
                    sortOrderLo = item->GetEntry();
                    sortOrderHi = ITEM_SORT_SPECIAL_ITEM << 24;
                }
                else
                {
                    switch (item->GetTemplate()->GetClass())
                    {
                    case (ITEM_CLASS_ARMOR):
                        switch (item->GetTemplate()->GetInventoryType())
                        {
                        case (INVTYPE_SHIELD):
                            sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                            sortOrderHi = ITEM_SORT_SHIELD << 24 ;
                            break;
                        case (INVTYPE_HEAD):
                            sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                            sortOrderHi = ITEM_SORT_HEAD << 24;
                            break;
                        case (INVTYPE_SHOULDERS):
                            sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                            sortOrderHi = ITEM_SORT_SHOULDERS << 24;
                            break;
                        case (INVTYPE_ROBE):
                        case (INVTYPE_CHEST):
                            sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                            sortOrderHi = ITEM_SORT_CHEST << 24;
                            break;
                        case (INVTYPE_WRISTS):
                            sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                            sortOrderHi = ITEM_SORT_WRISTS << 24;
                            break;
                        case (INVTYPE_HANDS):
                            sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                            sortOrderHi = ITEM_SORT_HANDS << 24;
                            break;
                        case (INVTYPE_WAIST):
                            sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                            sortOrderHi = ITEM_SORT_WAIST << 24;
                            break;
                        case (INVTYPE_LEGS):
                            sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                            sortOrderHi = ITEM_SORT_LEGS << 24;
                            break;
                        case (INVTYPE_FEET):
                            sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                            sortOrderHi = ITEM_SORT_FEET << 24;
                            break;
                        case (INVTYPE_CLOAK):
                            sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                            sortOrderHi = ITEM_SORT_CLOAK << 24;
                            break;
                        case (INVTYPE_NECK):
                        case (INVTYPE_FINGER):
                        case (INVTYPE_TRINKET):
                            sortOrderLo = (MAX_ITEM_LEVEL - item->GetEntry());
                            sortOrderHi = ITEM_SORT_ACCESSORY << 24;
                            break;
                        case (INVTYPE_BODY):
                        case (INVTYPE_TABARD):
                            sortOrderLo = (MAX_ITEM_LEVEL - item->GetEntry());
                            sortOrderHi = ITEM_SORT_BODY_TABARD << 24;
                            break;
                        default:
                            sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                            sortOrderHi = ITEM_SORT_OTHER_ITEMS << 24;
                            break;
                        }
                        break;
                    case (ITEM_CLASS_WEAPON):
                        sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                        sortOrderHi = ITEM_SORT_WEAPON << 24;
                        break;
                    case (ITEM_CLASS_CONSUMABLE):
                        sortOrderLo = item->GetEntry();
                        sortOrderHi = ITEM_SORT_CONSUMABLE << 24 | item->GetTemplate()->GetClass() << 16 | (MAX_ITEM_SUBCLASS_CONSUMABLE - item->GetTemplate()->GetSubClass());
                        break;
                    default:
                        sortOrderLo = (UINT32_MAX - item->GetEntry());
                        sortOrderHi = ITEM_SORT_OTHER_ITEMS << 24 | item->GetTemplate()->GetClass() << 16 | (MAX_ITEM_SUBCLASS_CONSUMABLE - item->GetTemplate()->GetSubClass());
                        break;
                    }
                }
                sortOrder = (static_cast<uint64>(sortOrderHi) << 32) | sortOrderLo;
                items.insert(std::make_pair(sortOrder, item));
                _player->RemoveItem(INVENTORY_SLOT_BAG_0, slot, true);
            }
        }

    for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
    {
        if (Bag* bag = _player->GetBagByPos(i))
        {
            if (!_player->GetBagSlotFlags(i - INVENTORY_SLOT_BAG_START).HasFlag(BagSlotFlags::DisableAutoSort))
                for (uint32 j = 0; j < GetBagSize(bag); j++)
                {
                    if (Item* item = GetItemInBag(bag, j))
                    {
                        if (item->GetEntry() == ITEM_HEARTHSTONE || item->GetEntry() == ITEM_GARRISON_HEARTHSTONE
                            || item->GetEntry() == ITEM_DALARAN_HEARTHSTONE || item->GetEntry() == ITEM_FLIGHT_MASTER_WHISTLE)
                        {
                            sortOrderLo = item->GetEntry();
                            sortOrderHi = ITEM_SORT_SPECIAL_ITEM << 24;
                        }
                        else
                        {
                            switch (item->GetTemplate()->GetClass())
                            {
                            case (ITEM_CLASS_ARMOR):
                                switch (item->GetTemplate()->GetInventoryType())
                                {
                                case (INVTYPE_SHIELD):
                                    sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                                    sortOrderHi = ITEM_SORT_SHIELD << 24;
                                    break;
                                case (INVTYPE_HEAD):
                                    sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                                    sortOrderHi = ITEM_SORT_HEAD << 24;
                                    break;
                                case (INVTYPE_SHOULDERS):
                                    sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                                    sortOrderHi = ITEM_SORT_SHOULDERS << 24;
                                    break;
                                case (INVTYPE_ROBE):
                                case (INVTYPE_CHEST):
                                    sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                                    sortOrderHi = ITEM_SORT_CHEST << 24;
                                    break;
                                case (INVTYPE_WRISTS):
                                    sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                                    sortOrderHi = ITEM_SORT_WRISTS << 24;
                                    break;
                                case (INVTYPE_HANDS):
                                    sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                                    sortOrderHi = ITEM_SORT_HANDS << 24;
                                    break;
                                case (INVTYPE_WAIST):
                                    sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                                    sortOrderHi = ITEM_SORT_WAIST << 24;
                                    break;
                                case (INVTYPE_LEGS):
                                    sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                                    sortOrderHi = ITEM_SORT_LEGS << 24;
                                    break;
                                case (INVTYPE_FEET):
                                    sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                                    sortOrderHi = ITEM_SORT_FEET << 24;
                                    break;
                                case (INVTYPE_CLOAK):
                                    sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                                    sortOrderHi = ITEM_SORT_CLOAK << 24;
                                    break;
                                case (INVTYPE_NECK):
                                case (INVTYPE_FINGER):
                                case (INVTYPE_TRINKET):
                                    sortOrderLo = (MAX_ITEM_LEVEL - item->GetEntry());
                                    sortOrderHi = ITEM_SORT_ACCESSORY << 24;
                                    break;
                                case (INVTYPE_BODY):
                                case (INVTYPE_TABARD):
                                    sortOrderLo = (MAX_ITEM_LEVEL - item->GetEntry());
                                    sortOrderHi = ITEM_SORT_BODY_TABARD << 24;
                                    break;
                                default:
                                    sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                                    sortOrderHi = ITEM_SORT_OTHER_ITEMS << 24;
                                    break;
                                }
                                break;
                            case (ITEM_CLASS_WEAPON):
                                sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                                sortOrderHi = ITEM_SORT_WEAPON << 24;
                                break;
                            case (ITEM_CLASS_CONSUMABLE):
                                sortOrderLo = item->GetEntry();
                                sortOrderHi = ITEM_SORT_CONSUMABLE << 24 | item->GetTemplate()->GetClass() << 16 | (MAX_ITEM_SUBCLASS_CONSUMABLE - item->GetTemplate()->GetSubClass());
                                break;
                            default:
                                sortOrderLo = (UINT32_MAX - item->GetEntry());
                                sortOrderHi = ITEM_SORT_OTHER_ITEMS << 24 | item->GetTemplate()->GetClass() << 16 | (MAX_ITEM_SUBCLASS_CONSUMABLE - item->GetTemplate()->GetSubClass());
                                break;
                            }
                        }
                        sortOrder = (static_cast<uint64>(sortOrderHi) << 32) | sortOrderLo;
                        items.insert(std::make_pair(sortOrder, item));
                        _player->RemoveItem(item->GetBagSlot(), item->GetSlot(), true);
                    }
                }
        }
    }

    for (auto itr = std::begin(items); itr != std::end(items); ++itr)
        _player->StoreItemInBag(itr->second);

    SendPacket(WorldPackets::Item::BagCleanupFinished().Write());
}

void WorldSession::HandleSortBankBags(WorldPackets::Item::SortBankBags& /*sortBankBags*/)
{
    std::multimap<uint64, Item*> items;
    uint32 sortOrderHi;
    uint32 sortOrderLo;
    uint64 sortOrder;

    //save all the items in all bags into a multimap: items and remove items from bank
    for (uint8 slot = BANK_SLOT_ITEM_START; slot < BANK_SLOT_ITEM_END; slot++)
    {
        if (Item* item = _player->GetItemByPos(INVENTORY_SLOT_BAG_0, slot))
        {
            if (item->GetEntry() == ITEM_HEARTHSTONE || item->GetEntry() == ITEM_GARRISON_HEARTHSTONE
                || item->GetEntry() == ITEM_DALARAN_HEARTHSTONE || item->GetEntry() == ITEM_FLIGHT_MASTER_WHISTLE)
            {
                sortOrderLo = item->GetEntry();
                sortOrderHi = ITEM_SORT_SPECIAL_ITEM << 24;
            }
            else
            {
                switch (item->GetTemplate()->GetClass())
                {
                case (ITEM_CLASS_ARMOR):
                    switch (item->GetTemplate()->GetInventoryType())
                    {
                    case (INVTYPE_SHIELD):
                        sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                        sortOrderHi = ITEM_SORT_SHIELD << 24;
                        break;
                    case (INVTYPE_HEAD):
                        sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                        sortOrderHi = ITEM_SORT_HEAD << 24;
                        break;
                    case (INVTYPE_SHOULDERS):
                        sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                        sortOrderHi = ITEM_SORT_SHOULDERS << 24;
                        break;
                    case (INVTYPE_ROBE):
                    case (INVTYPE_CHEST):
                        sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                        sortOrderHi = ITEM_SORT_CHEST << 24;
                        break;
                    case (INVTYPE_WRISTS):
                        sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                        sortOrderHi = ITEM_SORT_WRISTS << 24;
                        break;
                    case (INVTYPE_HANDS):
                        sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                        sortOrderHi = ITEM_SORT_HANDS << 24;
                        break;
                    case (INVTYPE_WAIST):
                        sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                        sortOrderHi = ITEM_SORT_WAIST << 24;
                        break;
                    case (INVTYPE_LEGS):
                        sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                        sortOrderHi = ITEM_SORT_LEGS << 24;
                        break;
                    case (INVTYPE_FEET):
                        sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                        sortOrderHi = ITEM_SORT_FEET << 24;
                        break;
                    case (INVTYPE_CLOAK):
                        sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                        sortOrderHi = ITEM_SORT_CLOAK << 24;
                        break;
                    case (INVTYPE_NECK):
                    case (INVTYPE_FINGER):
                    case (INVTYPE_TRINKET):
                        sortOrderLo = (MAX_ITEM_LEVEL - item->GetEntry());
                        sortOrderHi = ITEM_SORT_ACCESSORY << 24;
                        break;
                    case (INVTYPE_BODY):
                    case (INVTYPE_TABARD):
                        sortOrderLo = (MAX_ITEM_LEVEL - item->GetEntry());
                        sortOrderHi = ITEM_SORT_BODY_TABARD << 24;
                        break;
                    default:
                        sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                        sortOrderHi = ITEM_SORT_OTHER_ITEMS << 24;
                        break;
                    }
                    break;
                case (ITEM_CLASS_WEAPON):
                    sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                    sortOrderHi = ITEM_SORT_WEAPON << 24;
                    break;
                case (ITEM_CLASS_CONSUMABLE):
                    sortOrderLo = item->GetEntry();
                    sortOrderHi = ITEM_SORT_CONSUMABLE << 24 | item->GetTemplate()->GetClass() << 16 | (MAX_ITEM_SUBCLASS_CONSUMABLE - item->GetTemplate()->GetSubClass());
                    break;
                default:
                    sortOrderLo = (UINT32_MAX - item->GetEntry());
                    sortOrderHi = ITEM_SORT_OTHER_ITEMS << 24 | item->GetTemplate()->GetClass() << 16 | (MAX_ITEM_SUBCLASS_CONSUMABLE - item->GetTemplate()->GetSubClass());
                    break;
                }
            }
            sortOrder = (static_cast<uint64>(sortOrderHi) << 32) | sortOrderLo;
            items.insert(std::make_pair(sortOrder, item));
            _player->RemoveItem(INVENTORY_SLOT_BAG_0, item->GetSlot(), true);
        }
    }

    for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
    {
        if (Bag* bag = _player->GetBagByPos(i))
        {
            for (uint32 j = 0; j < GetBagSize(bag); j++)
            {
                if (Item* item = GetItemInBag(bag, j))
                {
                    if (item->GetEntry() == ITEM_HEARTHSTONE || item->GetEntry() == ITEM_GARRISON_HEARTHSTONE
                        || item->GetEntry() == ITEM_DALARAN_HEARTHSTONE || item->GetEntry() == ITEM_FLIGHT_MASTER_WHISTLE)
                    {
                        sortOrderLo = item->GetEntry();
                        sortOrderHi = ITEM_SORT_SPECIAL_ITEM << 24;
                    }
                    else
                    {
                        switch (item->GetTemplate()->GetClass())
                        {
                        case (ITEM_CLASS_ARMOR):
                            switch (item->GetTemplate()->GetInventoryType())
                            {
                            case (INVTYPE_SHIELD):
                                sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                                sortOrderHi = ITEM_SORT_SHIELD << 24;
                                break;
                            case (INVTYPE_HEAD):
                                sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                                sortOrderHi = ITEM_SORT_HEAD << 24;
                                break;
                            case (INVTYPE_SHOULDERS):
                                sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                                sortOrderHi = ITEM_SORT_SHOULDERS << 24;
                                break;
                            case (INVTYPE_ROBE):
                            case (INVTYPE_CHEST):
                                sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                                sortOrderHi = ITEM_SORT_CHEST << 24;
                                break;
                            case (INVTYPE_WRISTS):
                                sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                                sortOrderHi = ITEM_SORT_WRISTS << 24;
                                break;
                            case (INVTYPE_HANDS):
                                sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                                sortOrderHi = ITEM_SORT_HANDS << 24;
                                break;
                            case (INVTYPE_WAIST):
                                sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                                sortOrderHi = ITEM_SORT_WAIST << 24;
                                break;
                            case (INVTYPE_LEGS):
                                sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                                sortOrderHi = ITEM_SORT_LEGS << 24;
                                break;
                            case (INVTYPE_FEET):
                                sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                                sortOrderHi = ITEM_SORT_FEET << 24;
                                break;
                            case (INVTYPE_CLOAK):
                                sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                                sortOrderHi = ITEM_SORT_CLOAK << 24;
                                break;
                            case (INVTYPE_NECK):
                            case (INVTYPE_FINGER):
                            case (INVTYPE_TRINKET):
                                sortOrderLo = (MAX_ITEM_LEVEL - item->GetEntry());
                                sortOrderHi = ITEM_SORT_ACCESSORY << 24;
                                break;
                            case (INVTYPE_BODY):
                            case (INVTYPE_TABARD):
                                sortOrderLo = (MAX_ITEM_LEVEL - item->GetEntry());
                                sortOrderHi = ITEM_SORT_BODY_TABARD << 24;
                                break;
                            default:
                                sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                                sortOrderHi = ITEM_SORT_OTHER_ITEMS << 24;
                                break;
                            }
                            break;
                        case (ITEM_CLASS_WEAPON):
                            sortOrderLo = (MAX_ITEM_LEVEL - item->GetItemLevel(_player));
                            sortOrderHi = ITEM_SORT_WEAPON << 24;
                            break;
                        case (ITEM_CLASS_CONSUMABLE):
                            sortOrderLo = item->GetEntry();
                            sortOrderHi = ITEM_SORT_CONSUMABLE << 24 | item->GetTemplate()->GetClass() << 16 | (MAX_ITEM_SUBCLASS_CONSUMABLE - item->GetTemplate()->GetSubClass());
                            break;
                        default:
                            sortOrderLo = (UINT32_MAX - item->GetEntry());
                            sortOrderHi = ITEM_SORT_OTHER_ITEMS << 24 | item->GetTemplate()->GetClass() << 16 | (MAX_ITEM_SUBCLASS_CONSUMABLE - item->GetTemplate()->GetSubClass());
                            break;
                        }
                    }
                    sortOrder = (static_cast<uint64>(sortOrderHi) << 32) | sortOrderLo;
                    items.insert(std::make_pair(sortOrder, item));
                    _player->RemoveItem(item->GetBagSlot(), item->GetSlot(), true);
                }
            }
        }
    }

    for (auto itr = std::begin(items); itr != std::end(items); ++itr)
        _player->StoreItemInBank(itr->second);

    SendPacket(WorldPackets::Item::BagCleanupFinished().Write());
}

void WorldSession::HandleSortReagentBankBags(WorldPackets::Item::SortReagentBankBags& /*sortReagentBankBags*/)
{
     std::multimap<uint64, Item*> items;
    uint32 sortOrderHi;
    uint32 sortOrderLo;
    uint64 sortOrder;

    //save all the items in all bags into a multimap: items and remove items from bank
    for (uint8 slot = REAGENT_SLOT_START; slot < REAGENT_SLOT_END; ++slot)
    {
        if (Item* item = _player->GetItemByPos(INVENTORY_SLOT_BAG_0, slot))
        {
            sortOrderLo = (UINT32_MAX - item->GetEntry());
            sortOrderHi = item->GetTemplate()->GetClass() << 16 | (MAX_ITEM_SUBCLASS_TRADE_GOODS - item->GetTemplate()->GetSubClass());
            sortOrder = (static_cast<uint64>(sortOrderHi) << 32) | sortOrderLo;
            items.insert(std::make_pair(sortOrder, item));
            _player->RemoveItem(INVENTORY_SLOT_BAG_0, item->GetSlot(), true);
        }
    }

    for (auto itr = std::begin(items); itr != std::end(items); ++itr)
        _player->StoreItemInReagentBank(itr->second);


    SendPacket(WorldPackets::Item::BagCleanupFinished().Write());
}

void WorldSession::HandleRemoveNewItem(WorldPackets::Item::RemoveNewItem& removeNewItem)
{
    Item* item = _player->GetItemByGuid(removeNewItem.ItemGuid);
    if (!item)
    {
        TC_LOG_DEBUG("network", "WorldSession::HandleRemoveNewItem: Item ({}) not found for {}!", removeNewItem.ItemGuid.ToString(), GetPlayerInfo());
        return;
    }

    if (item->HasItemFlag(ITEM_FIELD_FLAG_NEW_ITEM))
    {
        item->RemoveItemFlag(ITEM_FIELD_FLAG_NEW_ITEM);
        item->SetState(ITEM_CHANGED, _player);
    }
}

void WorldSession::HandleChangeBagSlotFlag(WorldPackets::Item::ChangeBagSlotFlag const& changeBagSlotFlag)
{
    if (changeBagSlotFlag.BagIndex >= _player->m_activePlayerData->BagSlotFlags.size())
        return;

    if (changeBagSlotFlag.On)
    {
        //Only one priority can be available at the same time so we have to remove all flags (except Ignore Cleanup & Ignore Junk)
        if (_player->GetBagSlotFlags(changeBagSlotFlag.BagIndex).HasFlag(BagSlotFlags::PriorityEquipment))
            _player->RemoveBagSlotFlag(changeBagSlotFlag.BagIndex, BagSlotFlags::PriorityEquipment);
        if (_player->GetBagSlotFlags(changeBagSlotFlag.BagIndex).HasFlag(BagSlotFlags::PriorityConsumables))
            _player->RemoveBagSlotFlag(changeBagSlotFlag.BagIndex, BagSlotFlags::PriorityConsumables);
        if (_player->GetBagSlotFlags(changeBagSlotFlag.BagIndex).HasFlag(BagSlotFlags::PriorityTradeGoods))
            _player->RemoveBagSlotFlag(changeBagSlotFlag.BagIndex, BagSlotFlags::PriorityTradeGoods);
        if (_player->GetBagSlotFlags(changeBagSlotFlag.BagIndex).HasFlag(BagSlotFlags::PriorityJunk))
            _player->RemoveBagSlotFlag(changeBagSlotFlag.BagIndex, BagSlotFlags::PriorityJunk);
        if (_player->GetBagSlotFlags(changeBagSlotFlag.BagIndex).HasFlag(BagSlotFlags::PriorityQuestItems))
            _player->RemoveBagSlotFlag(changeBagSlotFlag.BagIndex, BagSlotFlags::PriorityQuestItems);
        _player->SetBagSlotFlag(changeBagSlotFlag.BagIndex, changeBagSlotFlag.FlagToChange);
    }
    else
        _player->RemoveBagSlotFlag(changeBagSlotFlag.BagIndex, changeBagSlotFlag.FlagToChange);
}

void WorldSession::HandleChangeBankBagSlotFlag(WorldPackets::Item::ChangeBankBagSlotFlag const& changeBankBagSlotFlag)
{
    if (changeBankBagSlotFlag.BagIndex >= _player->m_activePlayerData->BankBagSlotFlags.size())
        return;

    if(changeBankBagSlotFlag.On)
    {
        if (_player->GetBankBagSlotFlags(changeBankBagSlotFlag.BagIndex).HasFlag(BagSlotFlags::PriorityConsumables))
            _player->RemoveBankBagSlotFlag(changeBankBagSlotFlag.BagIndex, BagSlotFlags::PriorityConsumables);
        if (_player->GetBankBagSlotFlags(changeBankBagSlotFlag.BagIndex).HasFlag(BagSlotFlags::PriorityEquipment))
            _player->RemoveBankBagSlotFlag(changeBankBagSlotFlag.BagIndex, BagSlotFlags::PriorityEquipment);
        if (_player->GetBankBagSlotFlags(changeBankBagSlotFlag.BagIndex).HasFlag(BagSlotFlags::PriorityJunk))
            _player->RemoveBankBagSlotFlag(changeBankBagSlotFlag.BagIndex, BagSlotFlags::PriorityJunk);
        if (_player->GetBankBagSlotFlags(changeBankBagSlotFlag.BagIndex).HasFlag(BagSlotFlags::PriorityQuestItems))
            _player->RemoveBankBagSlotFlag(changeBankBagSlotFlag.BagIndex, BagSlotFlags::PriorityQuestItems);
        if (_player->GetBankBagSlotFlags(changeBankBagSlotFlag.BagIndex).HasFlag(BagSlotFlags::PriorityTradeGoods))
            _player->RemoveBankBagSlotFlag(changeBankBagSlotFlag.BagIndex, BagSlotFlags::PriorityTradeGoods);
        _player->SetBankBagSlotFlag(changeBankBagSlotFlag.BagIndex, changeBankBagSlotFlag.FlagToChange);
    }
    else
        _player->RemoveBankBagSlotFlag(changeBankBagSlotFlag.BagIndex, changeBankBagSlotFlag.FlagToChange);
}

void WorldSession::HandleSetBackpackAutosortDisabled(WorldPackets::Item::SetBackpackAutosortDisabled const& setBackpackAutosortDisabled)
{
    _player->SetBackpackAutoSortDisabled(setBackpackAutosortDisabled.Disable);
}

void WorldSession::HandleSetBackpackSellJunkDisabled(WorldPackets::Item::SetBackpackSellJunkDisabled const& setBackpackSellJunkDisabled)
{
    _player->SetBackpackSellJunkDisabled(setBackpackSellJunkDisabled.Disable);
}

void WorldSession::HandleSetBankAutosortDisabled(WorldPackets::Item::SetBankAutosortDisabled const& setBankAutosortDisabled)
{
    _player->SetBankAutoSortDisabled(setBankAutosortDisabled.Disable);
}
